package com.wwh.furns.web;


import com.wwh.furns.entity.Furn;
import com.wwh.furns.entity.Page;
import com.wwh.furns.service.FurnService;
import com.wwh.furns.service.impl.FurnServiceImpl;
import com.wwh.furns.utils.DataUtils;
import com.wwh.furns.utils.WebUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

/**
 * @author Albert
 * @date 2024/5/30-10:49
 * @describe
 */
public class FurnServlet extends BasicServlet {
    private final FurnService furnService = new FurnServiceImpl();

    /**
     * 使用模版设计模式+动态代理+反射的方案来实现list
     *
     * @param req
     * @param resp
     */
    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //System.out.println("FurnServlet list is called...");
        List<Furn> furns = furnService.queryFurns();

        //for (Furn furn : furns) {
        //    System.out.println(furn);
        //}

        //把furns放入request域
        req.setAttribute("furns", furns);

        //请求转发
        req.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(req, resp);
    }

    /**
     * 处理添加家具的请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        ////从http请求里面获取新家具的数据
        //String name = req.getParameter("name");
        //String maker = req.getParameter("maker");
        //String price = req.getParameter("price");
        //String sales = req.getParameter("sales");
        //String stock = req.getParameter("stock");
        //
        //
        ////创建Furn对象
        //Furn furn = new Furn(null, name, maker, new BigDecimal(price), Integer.parseInt(sales), Integer.parseInt(stock), "assets/images/product-image/default.jpg");

        //使用第二种方式对Furn进行封装
        //使用BeanUtils完成JavaBean对象的自动封装--需要导入相对应的包

        Furn furn = new Furn();

        DataUtils.copyParamToBean(req.getParameterMap(), furn);

        //System.out.println(furn);

        //添加furn对象
        boolean res = furnService.addFurn(furn);

        int pageNo = DataUtils.parseInt(req.getParameter("pageNo"), 1);

        if (res) {
            resp.sendRedirect(req.getContextPath() + "/manage/furnServlet?action=page&pageNo=" + pageNo);
        } else {
            resp.setContentType("text/html;charset=UTF-8");
            PrintWriter writer = resp.getWriter();
            writer.write("<a href=\"\\jiaju_mall\\views\\manage\\furn_add.jsp\"<a>add failed..click to add page..</a>");
            writer.flush();
            writer.close();
        }
    }

    public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        furnService.deleteFurnById(DataUtils.parseInt(req.getParameter("id"), 0));
        resp.sendRedirect(req.getContextPath() + "/manage/furnServlet?action=page&pageNo=" + req.getParameter("pageNo"));
    }

    /**
     * 处理回显家具的请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void showFurn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        Furn furn = furnService.queryFurnById(id);

        req.setAttribute("furn", furn);

        //req.setAttribute("pageNo", req.getParameter("pageNo"));//由于是请求转发，可以在furn_update界面使用param.pageNo代替

        req.getRequestDispatcher("/views/manage/furn_update.jsp").forward(req, resp);

    }

    public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = DataUtils.parseInt(req.getParameter("id"), 0);
        Furn furn = furnService.queryFurnById(id);
        if (furn != null) {


            //1. 判断是不是文件表单(enctype="multipart/form-data")
            if (ServletFileUpload.isMultipartContent(req)) {
                //System.out.println("OK");
                //2. 创建 DiskFileItemFactory 对象, 用于构建一个解析上传数据的工具对象
                DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
                //3. 创建一个解析上传数据的工具对象
                /**
                 *     表单提交的数据就是 input 元素
                 *     <input type="file" name="pic" id="" value="2xxx.jpg" onchange="prev(this)"/>
                 *     家居名: <input type="text" name="name"><br/>
                 *     <input type="submit" value="上传"/>
                 */
                ServletFileUpload servletFileUpload =
                        new ServletFileUpload(diskFileItemFactory);
                //解决接收到文件名是中文乱码问题
                servletFileUpload.setHeaderEncoding("utf-8");

                //4. 关键的地方, servletFileUpload 对象可以把表单提交的数据text / 文件
                //   将其封装到 FileItem 文件项中
                //   老师的编程心得体会: 如果我们不知道一个对象是什么结构[1.输出 2.debug 3. 底层自动看到]
                try {
                    List<FileItem> list = servletFileUpload.parseRequest(req);
                /*
                list==>

                [name=3.jpg, StoreLocation=D:\hspedu_javaweb\apache-tomcat-8.0.50-windows-x64\apache-tomcat-8.0.50\temp\xupload__7e34374f_17fce4168b1__7f4b_00000000.tmp, size=106398bytes, isFormField=false, FieldName=pic,
                name=null, StoreLocation=D:\hspedu_javaweb\apache-tomcat-8.0.50-windows-x64\apache-tomcat-8.0.50\temp\xupload__7e34374f_17fce4168b1__7f4b_00000001.tmp, size=6bytes, isFormField=true, FieldName=name]

                 */
                    //System.out.println("list==>" + list);
                    //遍历，并分别处理=> 自然思路
                    for (FileItem fileItem : list) {
                        //System.out.println("fileItem=" + fileItem);
                        //判断是不是一个文件=> 你是OOP程序员
                        if (fileItem.isFormField()) {//如果是true就是文本 input text
                            if ("name".equals(fileItem.getFieldName())) {
                                furn.setName(fileItem.getString("utf-8"));
                            } else if ("maker".equals(fileItem.getFieldName())) {
                                furn.setMaker(fileItem.getString("utf-8"));
                            } else if ("price".equals(fileItem.getFieldName())) {
                                furn.setPrice(new BigDecimal(fileItem.getString("utf-8")));
                            } else if ("sales".equals(fileItem.getFieldName())) {
                                furn.setSales(new Integer(fileItem.getString("utf-8")));
                            } else if ("stock".equals(fileItem.getFieldName())) {
                                furn.setStock(new Integer(fileItem.getString("utf-8")));
                            }
                        } else {//是一个文件

                            //用一个方法
                            //获取上传的文件的名字
                            String name = fileItem.getName();
                            System.out.println("上传的文件名=" + name);

                            //如果用户没有更新图片，name会是一个空串
                            if (!"".equals(name)) {
                                String oldImgPath = furn.getImgPath();

                                //把这个上传到 服务器的 temp下的文件保存到你指定的目录
                                //1.指定一个目录 , 就是我们网站工作目录下
                                String filePath = "/" + WebUtils.FURN_IMG6_DIRECTORY;
                                //2. 获取到完整目录 [io/servlet基础]
                                //  这个目录是和你的web项目运行环境绑定的. 是动态.
                                //fileRealPath=D:\hspedu_javaweb\fileupdown\out\artifacts\fileupdown_war_exploded\xupload\
                                String fileRealPath =
                                        req.getServletContext().getRealPath(filePath);
                                System.out.println("fileRealPath=" + fileRealPath);

                                //3. 创建这个上传的目录=> 创建目录?=> Java基础
                                File fileRealPathDirectory = new File(fileRealPath + "/" + WebUtils.getYearMonthDay());
                                System.out.println("图片存放路径=" + fileRealPathDirectory);
                                if (!fileRealPathDirectory.exists()) {//不存在，就创建
                                    fileRealPathDirectory.mkdirs();//创建
                                }

                                //4. 将文件拷贝到fileRealPathDirectory目录
                                //   构建一个上传文件的完整路径 ：目录+文件名
                                //   对上传的文件名进行处理, 前面增加一个前缀，保证是唯一即可, 不错
                                name = UUID.randomUUID().toString() + "_" + System.currentTimeMillis() + "_" + name;
                                String fileFullPath = fileRealPathDirectory + "/" + name;
                                fileItem.write(new File(fileFullPath));
                                fileItem.getOutputStream().close();

                                //更新家居图片路径
                                furn.setImgPath(WebUtils.FURN_IMG6_DIRECTORY + "/" + WebUtils.getYearMonthDay() + "/" + name);

                                //删除原来家居的图片
                                File file = new File(req.getServletContext().getRealPath(oldImgPath));
                                if(file.exists()) {
                                    file.delete();
                                }
                            }
                        }

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("不是文件表单...");
            }
            //更新家居
            furnService.updateFurn(furn);
            System.out.println("更新家居成功！");

            //请求转发到更新成功提示页面
            req.getRequestDispatcher("/views/manage/update_ok.jsp").forward(req, resp);
        }


        ////将提交的修改信息封装成一个Furn
        //Furn furn = DataUtils.copyParamToBean(req.getParameterMap(), new Furn());
        //furnService.updateFurn(furn);
        //int pageNo = DataUtils.parseInt(req.getParameter("pageNo"), 1);
        //resp.sendRedirect(req.getContextPath() + "/manage/furnServlet?action=page&pageNo=" + pageNo);

    }

    /**
     * 处理分页请求
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNo = DataUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = DataUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);

        Page<Furn> page = furnService.page(pageNo, pageSize);

        //把page放入request域
        req.setAttribute("page", page);

        //请求转发
        req.getRequestDispatcher("/views/manage/furn_manage.jsp").forward(req, resp);
    }
}
